package com.ash.other;

import com.ash.util.ConnectionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/6 19:20
 * @Author : Chen Chao
 * @File : connection.com.ash.other.Test03.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 事务处理
 */
public class Test03 {
    public static void main(String[] args) {
        int fromId=1;
        int toId=2;
        int money=1000;
        test01(fromId,toId,money);
    }

    private static void test01(int fromId,int toId,int money) {
        int accountMoney;
        PreparedStatement ps=null;
        ResultSet resultSet=null;
        Connection connection = ConnectionUtil.getConnection();

        try {
            ps = Objects.requireNonNull(connection).
                    prepareStatement("select money FROM account where id=?");
            ps.setObject(1,fromId);
            resultSet = ps.executeQuery();
            if(resultSet.next()){
                 accountMoney = resultSet.getInt("money");
            }
            else {
                System.out.println("没有这个用户");
                return;
            }
            if(accountMoney<money){
                throw  new RuntimeException("钱不够");
                /*运行时异常编译时可以不捕获处理，不会报错*/
                /*如果运行时异常必然会产生，不处理后面代码不执行*/
            }

            try {
                /*关闭自动提交，开启事务*/
                connection.setAutoCommit(false);
                /*扣除*/
                ps=connection.prepareStatement("update account set money=money-? where id=?");
                ps.setObject(1,money);
                ps.setObject(2,fromId);
                ps.executeUpdate();
                System.out.println("钱已扣除，正在转入用户！");

                /*安排一个未知错误，送给catch*/
                //int i=5/0;
                /*转入*/
                ps=connection.prepareStatement("update account set money=money+? where id=?");
                ps.setObject(1,money);
                ps.setObject(2,toId);
                ps.executeUpdate();
                System.out.println("钱到账！");

                connection.commit();
                System.out.println("操作成功！");

                /*使用Exception捕获异常，如果漏掉执行的操作仍然占用着资源*/
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("出现未知错误，操作撤销");
                /*数据库并不知道你当机了，执行的操作仍然占用着资源*/
                connection.rollback();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection,ps,resultSet);
        }

        System.out.println("顺利执行！");
    }

}
